package com.wjs.juc.CAS;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * ABA问题的解决
 */
public class AtomicStampedDemo2 {
    static AtomicStampedReference<Integer> reference=new AtomicStampedReference(100,1);
    public static void main(String[] args) {
        new Thread(()->{
            int stamp = reference.getStamp();
            System.out.println(Thread.currentThread().getName()+"第一次版本号为"+stamp);
            try {
                TimeUnit.MILLISECONDS.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            reference.compareAndSet(100,101,reference.getStamp(),reference.getStamp()+1);
            System.out.println(Thread.currentThread().getName()+"值为"+reference.getReference()+"第二次版本号为"+reference.getStamp());
            reference.compareAndSet(101,100,reference.getStamp(),reference.getStamp()+1);
            System.out.println(Thread.currentThread().getName()+"值为"+reference.getReference()+"第三次版本号为"+reference.getStamp());
        },"t1").start();

        new Thread(()->{
            int stamp = reference.getStamp();
            System.out.println(Thread.currentThread().getName()+"第一次版本号为"+stamp);
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+":"+reference.getReference()+":"+reference.compareAndSet(100, 2022, stamp, stamp + 1));
        },"t2").start();
    }
}
